package com.njym.payment.wxpay.Server.impl; /**
 * @Title: WXserviceImpl
 * @ProjectName family-security
 * @Description: TODO
 * @author 71705
 * @date 2020/2/2513:34
 */

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.njym.payment.wxpay.Server.WXConfigUtil;
import com.njym.payment.wxpay.Server.WXservice;
import com.njym.payment.wxpay.Server.WxMD5Util;
import com.njym.payment.wxpay.properties.WxPayAppProperties;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @program: family-security
 *
 * @description:
 *
 * @author: lijie
 *
 * @create: 2020-02-25 13:34
 **/
@Service
public class WXserviceImpl implements WXservice {

    public static final String TRADE_TYPE_APP = "APP";






    /**
     * 调用官方SDK 获取预支付订单等参数
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> dounifiedOrder(WxPayAppProperties wxPayAppProperties,String ip,String notifyUrl) throws Exception {


        //生成商户订单号，不可重复


        BigDecimal bd = new BigDecimal(wxPayAppProperties.getTotalAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);

        //价格






        WxMD5Util md5Util = new WxMD5Util();
        Map<String, String> returnMap = new HashMap<>();
        WXConfigUtil config = new WXConfigUtil();
        WXPay wxpay = new WXPay( config);
        Map<String, String> data = new HashMap<>();

        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());

        String body = "购买" + wxPayAppProperties.getBody();
        data.put("body", body);
        data.put("out_trade_no", wxPayAppProperties.getOutTradeNo());

        data.put("total_fee", bd.multiply(new BigDecimal(100)).intValue()+"");
        //自己的服务器IP地址
        data.put("spbill_create_ip", ip);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", notifyUrl);
        //交易类型
        data.put("trade_type", TRADE_TYPE_APP);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        String sign1 = md5Util.getSign(data);
        data.put("sign", sign1);

        try {
            //使用官方API请求预付订单
            Map<String, String> response = wxpay.unifiedOrder(data);
            System.out.println(response);
            String returnCode = response.get("return_code");    //获取返回码
            //若返回码为SUCCESS，则会返回一个result_code,再对该result_code进行判断
            if (returnCode.equals("SUCCESS")) {//主要返回以下5个参数
                String resultCode = response.get("result_code");
                returnMap.put("appid", response.get("appid"));
                returnMap.put("mch_id", response.get("mch_id"));
                returnMap.put("nonce_str", response.get("nonce_str"));
                returnMap.put("sign", response.get("sign"));
                if ("SUCCESS".equals(resultCode)) {//resultCode 为SUCCESS，才会返回prepay_id和trade_type
                    //获取预支付交易回话标志
                    returnMap.put("trade_type", response.get("trade_type"));
                    returnMap.put("prepay_id", response.get("prepay_id"));
                    return returnMap;
                } else {
                    //此时返回没有预付订单的数据
                    return returnMap;
                }
            } else {
                return returnMap;
            }
        } catch (Exception e) {
            System.out.println(e);
            //系统等其他错误的时候
        }
        return returnMap;
    }






    /**
     * 生成邀请码
     * @return
     */
    public String genRandomNum(){
        int  maxNum = 36;
        int i;
        int count = 0;
        char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
            'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z',  '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < 5){
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return pwd.toString();
    }


}
